package com.lzy.mall.ware.listener;


import com.lzy.mall.common.constant.MQConstant;
import com.lzy.mall.common.to.OrderTo;
import com.lzy.mall.common.to.mq.StockLockedTo;
import com.lzy.mall.ware.service.WmsWareSkuService;
import com.rabbitmq.client.Channel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author lzy
 * @date 2021/10/11 16:27
 */
@Component
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
@RabbitListener(queues = MQConstant.stockReleaseQueue)
@Slf4j
public class StockReleaseListener {
    private final WmsWareSkuService wareSkuService;

    /**
     * 库存自动解锁
     * 1、下订单成功，库存锁定成功，接下来的业务调用失败，导致库存回滚。之前锁定的库存就要自动解锁。
     * 2、下订单失败，锁库存失败
     *
     * 只要解锁库存的消息失败。一定要告诉服务器此次解锁失败。启动手动ack机制
     *
     * @param to
     * @param message
     */
    @RabbitHandler
    public void handleStockLockedRelease(StockLockedTo to, Message message, Channel channel) throws Exception {
        System.out.println("收到解锁库存的消息");
        System.out.println("参数"+to);
        System.out.println("消息：" + message);
        try{
            wareSkuService.unlockStock(to);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            log.info("队列异常：{}",e.getMessage());
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }

    /**
     * 接收关闭订单发过来的消息，进行库所解锁
     * @param to
     * @param message
     * @param channel
     * @throws Exception
     */
    @RabbitHandler
    public void handleOrderCloseRelease(OrderTo to, Message message, Channel channel) throws Exception {
        System.out.println("接收关闭订单消息，解锁库存");
        try{
            wareSkuService.unlockStock(to);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            log.info("队列异常：{}",e.getMessage());
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }
}
